﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.TemplateLanguage.Properties;

namespace MethodWorx.CMS.TemplateLanguage.Parsers.Content
{
    public class Count : IParser
    {
        [ContentTemplateProperty]
        public string Template
        {
            get; set;
        }
        public object Parse(Web.CmsRequestContext context, IEnumerable<object> stack, Dictionary<string, object> parameters)
        {
            var page = this.GetPageFromStack(stack);
            if(page != null)
            {
                int count = 0;
                foreach(var contentItem in page.ChildContent)
                {
                    if (string.IsNullOrEmpty(this.Template))
                        count++;
                    else if (this.Template.ToLower() == contentItem.Template.Name.ToLower())
                        count++;
                }

                return count;
            }

            return null;
        }

        /// <summary>
        /// Locate either the page relating to the content item on the stack
        /// Or, the current page, whichever comes first
        /// </summary>
        /// <param name="stack"></param>
        /// <returns></returns>
        private MethodWorx.CMS.Content.Page GetPageFromStack(IEnumerable<object> stack)
        {
            foreach(var item in stack)
            {
                if (item is CMS.Content.ContentItem)
                    return ((CMS.Content.ContentItem) item).Page;
                else if(item is CMS.Content.Page)
                    return (CMS.Content.Page) item;

            }

            return null;
        }

        public string Name
        {
            get { return "Count"; }
        }

        public string Namespace
        {
            get { return "Content"; }
        }
    }
}
